<template>
  <el-dialog
    :title="`${tagDetail.id ? '修改' : '新增'}标签`"
    :visible="showDialog"
    width="25%"
    @close="handleClose"
    @open='handleOpen'
  >
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="所属学科" prop="subjectID" v-if="!$route.query.name">
        <el-select placeholder="请选择" v-model="form.subjectID">
          <el-option
          v-for="item in subjectList"
          :key="item.id"
          :label="item.subjectName"
          :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="标签名称" prop="tagName">
        <el-input v-model="form.tagName"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确定</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { list as getSubjectList } from '@/api/hmmm/subjects.js'
import { add, update } from '@/api/hmmm/tags.js'

export default {
  name: 'TagsAdd',
  watch: {
    tagDetail () {
      this.form.tagName = this.tagDetail.tagName
      this.form.subjectID = this.tagDetail.subjectID
    }
  },
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    // 选择的标签详情
    tagDetail: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      subjectList: [], // 学科列表
      form: {
        tagName: '', // 标签名称
        subjectID: null // 学科ID
      },
      rules: {
        tagName: [
          { required: true, message: '请输入标签名称', trigger: 'blur' }
        ],
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    dialogTitle () {
      return this.form.id ? '编辑标签' : '添加标签'
    }
  },
  methods: {
    handleClose () {
      this.$emit('closeDialog')
      // 手动清空
      this.form = {
        tagName: '', // 标签名称
        subjectID: null // 学科ID
      }
    },
    // 弹窗打开
    handleOpen () {
      this.getSubjectList()
    },
    // 获取学科列表
    async getSubjectList () {
      const { data } = await getSubjectList({ page: 1, pagesize: 100 })
      this.subjectList = data.items
    },
    // 确认按钮
    handleSubmit () {
      // 判断是编辑还是提交
      this.$refs.form.validate(async (flag) => {
        if (!flag) return
        if (this.tagDetail.id) {
          await update({ ...this.form, id: this.tagDetail.id })
          this.$message.success('修改成功')
        } else {
          if (this.$route.query.id) {
            await add({ ...this.form, subjectID: +this.$route.query.id })
          } else {
            await add(this.form)
          }
          this.$message.success('添加成功')
        }
        this.$emit('add-tags')// 子传父更新数据
        this.handleClose()
      })
    }
  }
}
</script>

<style scoped lang='scss'>
::v-deep {
  .el-dialog__footer {
    text-align: right;
  }
}
</style>
